package com.xinlong.shop.api.blind;

import cn.hutool.core.util.StrUtil;
import com.wechat.pay.java.service.payments.jsapi.model.PrepayWithRequestPaymentResponse;
import com.xinlong.shop.api.common.BuyerBaseController;
import com.xinlong.shop.core.blind.entity.BlindBox;
import com.xinlong.shop.core.blind.entity.BlindBoxOrder;
import com.xinlong.shop.core.blind.entity.BlindBoxOrderItem;
import com.xinlong.shop.core.blind.entity.BlindBoxOrderStatusEnum;
import com.xinlong.shop.core.blind.entity.dto.BlindBoxOrderDTO;
import com.xinlong.shop.core.blind.entity.vo.BlindBoxOrderVO;
import com.xinlong.shop.core.blind.mapstruct.BlindBoxOrderVOStruct;
import com.xinlong.shop.core.blind.service.IBlindBoxOrderItemService;
import com.xinlong.shop.core.blind.service.IBlindBoxOrderService;
import com.xinlong.shop.core.blind.service.IBlindBoxService;
import com.xinlong.shop.core.member.service.IMemberService;
import com.xinlong.shop.framework.common.R;
import com.xinlong.shop.framework.core.entity.Member;
import com.xinlong.shop.framework.security.constant.SecurityConstants;
import com.xinlong.shop.framework.security.util.TokenUtil;
import com.xinlong.shop.framework.service.ISysSettingService;
import com.xinlong.shop.framework.weixin.service.WeiXinMpService;
import io.swagger.annotations.*;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author Sylow
 * @Description 用户端盲盒接口
 * @Date: Created in 13:48 2023/6/14
 */
@Validated      // get请求验证参数时需要
@RestController
@Api(tags = "买家盲盒订单API")
@RequestMapping("/buyer/blind-box-order")
public class BuyerBlindBoxOrderController extends BuyerBaseController {

    private final IBlindBoxService blindBoxService;
    private final IBlindBoxOrderService blindBoxOrderService;
    private final IBlindBoxOrderItemService blindBoxOrderItemService;
    private final ISysSettingService sysSettingService;
    private final WeiXinMpService weiXinMpService;
    private final BlindBoxOrderVOStruct blindBoxOrderVOStruct;

    public BuyerBlindBoxOrderController(IBlindBoxService blindBoxService, IMemberService memberService, TokenUtil tokenUtil, IBlindBoxOrderService blindBoxOrderService, IBlindBoxOrderItemService blindBoxOrderItemService, ISysSettingService sysSettingService, WeiXinMpService weiXinMpService, BlindBoxOrderVOStruct blindBoxOrderVOStruct) {
        super(memberService, tokenUtil);
        this.blindBoxService = blindBoxService;
        this.blindBoxOrderService = blindBoxOrderService;
        this.blindBoxOrderItemService = blindBoxOrderItemService;
        this.sysSettingService = sysSettingService;
        this.weiXinMpService = weiXinMpService;
        this.blindBoxOrderVOStruct = blindBoxOrderVOStruct;
    }

    @ApiOperation(value = "创建盲盒订单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "blindBoxId", value = "盲盒商品id", required = true, paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "ruleId", value = "价格规则id", required = true, paramType = "query", dataType = "string"),
            @ApiImplicitParam(name = "token", value = "token", required = true, paramType = "header", dataType = "string")
    })
    @ApiResponses(@ApiResponse(code = 200, message = "操作成功", response = BlindBoxOrder.class))
    @RequestMapping(value = "/create-order", method = RequestMethod.POST, produces = "application/json")
    public R createOrder(String code, String openid, @NotNull(message = "盲盒商品id不能为空") Integer blindBoxId, @NotBlank(message = "价格规则id不能为空") String ruleId, @RequestHeader(value = SecurityConstants.TOKEN_HEADER, required = true) String token){
        BlindBox blindBox = blindBoxService.getById(blindBoxId);
        if (blindBox == null) {
            return R.error("盲盒商品不存在");
        }

        Member member = getMember(token);
        if (member == null) {
            return R.error("用户不存在");
        }
        BlindBoxOrder blindBoxOrder = blindBoxOrderService.createOrder(blindBox, ruleId, member.getId());

        Map<String,Object> settings = sysSettingService.getSetting();
        Map<String, Object> result = new HashMap<>();

        boolean openWeixinPay = (boolean) settings.get("openWeixinPay");
        if (openWeixinPay) {
            if (StrUtil.isBlank(openid)) {
                openid = weiXinMpService.getOpenId(code);
                if (StrUtil.isBlank(openid)) {
                    return R.error("操作失败，请重试");
                }
            }
            PrepayWithRequestPaymentResponse response = weiXinMpService.pay(blindBoxOrder.getOrderSn(), openid,
                    blindBoxOrder.getPrice(), blindBox.getBlindBoxName());

            result.put("openWeixinPay", openWeixinPay);
            result.put("response", response);
            result.put("openid", openid);   // 返回前端做缓存，暂时不保存到后端
        } else {
            result.put("openWeixinPay", openWeixinPay);
        }

        return R.success(result);
    }

    @ApiOperation(value = "获取当前登录会员盲盒仓库内订单信息")
    @ApiResponses(@ApiResponse(code = 200, message = "操作成功", response = BlindBoxOrderVO.class))
    @RequestMapping(value = "/warehouse", method = RequestMethod.GET,  produces = "application/json")
    public R warehouse(@RequestHeader(value = SecurityConstants.TOKEN_HEADER, required = true) String token){
        Member member = getMember(token);
        // 得到盲盒订单列表
        List<BlindBoxOrderDTO> orderDTOList = this.blindBoxOrderService.findByMemberId(member.getId());
        // 转换VO
        List<BlindBoxOrderVO> orderVOList = blindBoxOrderVOStruct.toBlindBoxOrderVOList(orderDTOList);
        // 得到所有的盲盒订单项
        List<BlindBoxOrderItem> orderItemList = blindBoxOrderItemService.findByMemberId(member.getId());

        // 组织数据
        for (BlindBoxOrderVO orderVO : orderVOList) {
            Integer orderStatus = orderVO.getStatus();
            // 如果是已领取或已完成的订单，不显示具体的订单项
            if (orderStatus.intValue() == BlindBoxOrderStatusEnum.PICK_UP.getCode() || orderStatus.intValue() == BlindBoxOrderStatusEnum.COMPLETE.getCode()) {
                continue;
            }
            List<BlindBoxOrderItem> orderItemListTemp = new ArrayList<>();
            for(BlindBoxOrderItem orderItem : orderItemList){
                if(orderItem.getBlindBoxOrderId().equals(orderVO.getId())){
                    // 如果是未换购 或者其他状态的 显示
                    if (orderItem.getStatus() == 0) {
                        orderItemListTemp.add(orderItem);
                    }
                }
            }
            orderVO.setItemList(orderItemListTemp);
        }

        return R.success(orderVOList);
    }

}
